package com.fyy.netty.chapter02.c1;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;

/**
 * @Author fyy
 * @Description
 * @Date 2021/4/26 14:33
 */
public class EventLoopClient {

    public static void main(String[] args) throws InterruptedException {
        ChannelFuture future = new Bootstrap()
                .group(new NioEventLoopGroup(1))
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel sc) throws Exception {
                        sc.pipeline().addLast(new StringEncoder());
                    }
                }).connect(new InetSocketAddress("127.0.0.1", 8080));

        //使用sync同步阻塞
        future.sync(); //阻塞直到连接建立
        Channel channel = future.channel();
        channel.writeAndFlush("hello world");

        //使用addListener异步处理
        future.addListener(new ChannelFutureListener() {
            //连接建立执行operationComplete方法
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                Channel channel = future.channel();
                channel.writeAndFlush("hello world");
            }
        });
    }

}
